package com.zdp.jpa.test.control;

import com.zdp.jpa.test.entity.MemberCardOrder;
import com.zdp.jpa.test.entity.MemberCardRule;
import com.zdp.jpa.test.repository.MemberCardOrderRepository;
import com.zdp.jpa.test.repository.MemberCardRuleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author ZhengDp
 * @Date 2024/5/14 21:23
 * @Description 实惠卡数据造数
 */
@RestController
public class MemberCardController {

    private long orderCount = 800_0000;

    private long ruleCount = 1200;

    private int batchNum = 6667;

    @Autowired
    private MemberCardRuleRepository memberCardRuleRepository;

    @Autowired
    private MemberCardOrderRepository memberCardOrderRepository;

    private MemberCardController controller = this;



    // 造数据
    @GetMapping("/hello")
    public String test() throws Exception{
        for(int i =0;i<12;i++) {
            final int c = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        controller.run("线程" + c);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();
        }



        return "success";
    }

    public void run(String msg) throws Exception{
        int count = 0;
        for(int i =0;i<100;i++) {
            MemberCardRule memberCardRule = MemberCardRule.generateRandomRule();
            List<MemberCardOrder> memberCardOrders = IntStream.range(0, batchNum).mapToObj(item -> {
                MemberCardOrder memberCardOrder = MemberCardOrder.generateRandomOrder();
                memberCardOrder.setRuleId(memberCardRule.getId());
                return memberCardOrder;
            }).collect(Collectors.toList());
            memberCardOrderRepository.saveAll(memberCardOrders);
            count += memberCardOrders.size();
            System.out.println("线程:"+msg+" 目前插入:" + count + "条");
            Thread.sleep(100);
            memberCardRuleRepository.save(memberCardRule);
        }
    }

}


